<!DOCTYPE html>

<html>

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AJAX</title>
</head>

<body>

    <h3>用原生JavaScript实现异步请求</h3>

    <input type="text" name="username">

    <p class="message"></p>

    <script type="text/javascript">
        (() => {

            let text = document.querySelector('input[name=username]');

            if (text) {
                let listener = () => {
                    let name = text.getAttribute('name');
                    let value = text.value; // 获得输入框中的内容
                    // 预备向服务器发送的数据 ( 即 name=value 形式的 字符串 )
                    const data = name + '=' + value;

                    if (value && (value = value.trim())) {
                        // 1、创建XMLHttpRequest实例
                        let xhttp = new XMLHttpRequest();

                        let loadListener = e => {
                            let t = e.target;
                            console.log(t === xhttp);
                            let x = t.response;
                            console.log(x, typeof(x));
                            x = JSON.parse(x); // 将标准JSON格式的字符串解析为JavaScript对象
                            console.log(x.success, x.message);

                            let p = text.nextElementSibling;
                            console.log(p);
                            p.style.color = x.success ? 'green' : 'red';
                            p.innerHTML = x.message;
                        }

                        // 2、监听响应是否成功
                        xhttp.addEventListener('load', loadListener, false);

                        const method = 'post';
                        const url = '/check';
                        // 3、连接
                        xhttp.open(method, url);

                        // 4、若请求方式为POST则需要设置请求头
                        if ('post' === method.toLowerCase()) {
                            xhttp.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
                        }

                        // 5、发送请求(并通过send函数的参数发送数据)
                        xhttp.send(data);
                    }
                }
                text.addEventListener('blur', listener, false);
            }
        })();
    </script>

</body>

</html>